<?php
declare (strict_types = 1);

namespace app\controller;


use app\common\model\InterstTags;
use app\common\model\UserLoginLog;
use app\common\validate\Login;
use app\common\validate\Register;
use think\facade\Cookie;
use think\facade\Db;
use think\facade\Session;
use think\facade\View;
use think\Request;
use think\exception\ValidateException;

class User extends Common
{
    public function __construct()
    {
        parent::__construct();
    }
    public function login()
    {

        if(\think\facade\Request::isPost()){
            $d = \think\facade\Request::post();
            try {
                $result = validate(Login::class)->check($d);
                if (true !== $result) {
                    // 验证失败 输出错误信息
                    return json(["code"=>4000,"msg"=>$result]);
                }
                $user = Db::name("user")->where("username",$d["username"])
                    ->whereOr("phone",$d["username"])
                    ->whereOr("email",$d["username"])
                    ->find();
                if(!$user){
                    return json(["code"=>4000,"msg"=>"用户不存在"]);
                }
                if($user["status"] != 1){
                    return json(["code"=>4000,"msg"=>"用户被封禁"]);
                }

                if($user["password"] != md5($d["password"])){
                    return json(["code"=>4000,"msg"=>"密码错误"]);
                }
                //免登录
                Cookie::set("index_user",json_encode($user));

                $token = jwt_encode($user);
                $user["token"] = $token;
                //更新用户登录信息
                $update=[
                    "token"=>$token,
                    "last_time" => time(),
                    "last_ip"=>\think\facade\Request::ip(),
                    "login_count" =>$user["login_count"] +1
                ];

                //登录日志
                $log["uid"] = $user["id"];
                $log["nickname"] = $user["nickname"];
                $log["ip"] = \request()->ip();
                $log["devicename"] = "web";
                $log["device"] = "pc";
                $log["url"] = \request()->url();
                UserLoginLog::create($log);

                $res = Db::name("user")->where("id",$user["id"])->update($update);
                Session::set("index_user",$user);
                return json(["code"=>200,"msg"=>"登录成功","token"=>$token]);

            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                return json(["code"=>4000,"msg"=>$e->getError()]);
            }
        }
        return  view();
    }

    //获取所有的兴趣标签
    public function tags()
    {
        $tags = InterstTags::where("status",1)->select();
        return json(["code"=>200,"msg"=>"成功","data"=>$tags]);
    }

    public function userinfo()
    {
        $token = input("param.token");

        $u = jwt_decode($token);


        $user = \app\common\model\User::where("id",$u->uid)->withoutField("password",true)->find();
        if($user){
            return json(["code"=>200,"msg"=>"成功","data"=>$user]);
        }else{
            return json(["code"=>4000,"msg"=>"失败","data"=>""]);
        }
    }

    //用户注册
    public function register()
    {
        if(\think\facade\Request::isPost()){
            $d = \think\facade\Request::post();
            try {

                $result = validate(Register::class)->check($d);
                if (true !== $result) {
                    // 验证失败 输出错误信息
                    return json(["code"=>4000,"msg"=>$result]);
                }
                $d["password"] = md5($d["password"]);
                if(!isset($d["nickname"])){
                    $d["nickname"] = "pc".nickname(1);
                }
                $d["from"]="官网";

                $mod = new \app\common\model\User();
                if($uid = $mod->save($d)){
                    //$user = Db::name("user")
                    //    ->find($uid);
                    //$token = jwt_encode($user);
                    //$user["token"] = $token;
                    ////更新用户登录信息
                    //$update=[
                    //    "token"=>$token,
                    //    "last_time" => time(),
                    //    "last_ip"=>\think\facade\Request::ip(),
                    //    "login_count" =>$user["login_count"] +1
                    //];
                    //$res = Db::name("user")->where("id",$user["id"])->update($update);
                    //Session::set("index_user",$user);
                    //Cookie::set("index_user",json_encode($user));
                    return json(["code"=>200,"msg"=>"注册成功，2s 后跳转登录页..."]);
                }else{
                    return json(["code"=>4000,"msg"=>"请稍后再试"]);
                }

            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                return json(["code"=>4000,"msg"=>$e->getError()]);
            }
        }
        return  view();
    }

    //退出登录
    public function logout()
    {
        if(\think\facade\Request::isAjax()){
            $token = input("post.token");
            $user = jwt_decode($token);
            Session::delete("index_user");
            Cookie::delete("index_user");
            return json(["code"=>200,"msg"=>"成功"]);
        }else{
            Session::clear();
            $url =url('index/index');
            header("Location:{$url}");
        }

    }

    //自动登录
    public function autologin()
    {
        $token = input("post.token");
        $user = jwt_decode($token);
        if(!Session::get("index_user")){
            $index_user = \app\common\model\User::where("id",$user->uid)->find();
            Session::set("index_user",$index_user);

            //登录日志
            $log["uid"] = $index_user["id"];
            $log["nickname"] = $index_user["nickname"];
            $log["ip"] = \request()->ip();
            $log["devicename"] = "web";
            $log["device"] = "pc";
            $log["url"] = \request()->url();
            UserLoginLog::create($log);

            if($index_user){
                return json(["code"=>200,"msg"=>"自动登录成功"]);
            }
        }else{
            return json(["code"=>201,"msg"=>"用户登录状态有效-无需自动登录"]);
        }



    }

    //我的资料
    public function info()
    {
        $user = $this->user;
        if(!$user){
            return redirect((string) url('index/index',['redirect' => 'index/user/index']));
        }
        return  view();
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {

        $user = $this->user;
        if(!$user || !isset($user)){
            return redirect((string) url('index/index',['redirect' => 'index/user/index']));
        }
        return  view();
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $user = $this->user;
        if(!$user){
            return redirect((string) url('index/index',['redirect' => 'index/user/index']));
        }
        $d = input("post.");
        $mod = new \app\common\model\User();
        $res = $mod->where("id",Session::get("index_user.id"))
            ->save($d);
        $user = $mod->find(Session::get("index_user.id"));
        Session::set("index_user",$user);
        if($res){
            return json(["code"=>200,"msg"=>"成功"]);
        }else{
            return json(["code"=>4000,"msg"=>"稍后再试"]);
        }
    }


    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
